<?php
/**
 * @title 面试题 08.03. 魔术索引 - 剪枝
 * @author start2004
 */

class Solution {

    /**
     * @param Integer[] $nums
     * @return Integer
     */
    function findMagicIndex($nums) {
        /**
         * @since 2021-01-05 长度
         */
        $len = count($nums);

        /**
         * @since 2021-01-05 尝试剪枝长度
         */
        if($len > $nums[$len-1]+1){
            $len = $nums[$len-1]+1;
        } else {}
        // $len = min($len, $n);
        // return $len;

        /**
         * @since 2021-01-05 迭代
         */
        for($i=0; $i<$len;){
            if($i == $nums[$i]){
                return $i;
            } else {
                // $i = max($i+1, $nums[$i]);
                if($nums[$i] > $i){
                    $i = $nums[$i];
                } else {
                    $i++;
                }
            }
        }

        /**
         * @return
         */
        return -1;
    }
}




/**
 * @url http://127.0.0.1/leetcode/202007/2020.07.31_7.php
 */
$datas = [
    // [0, 2, 3, 4, 5],
    [1, 4, 4, 4, 4],
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof(2);
foreach ($datas as $data){
    var_dump($data);

    $obj = new Solution();
    $result = $obj->findMagicIndex($data);
    var_dump($result);
    echo str_repeat("<br>", 3);
}
$xhprof->end();
